import React, { useState, useEffect } from 'react';
const { ipcRenderer } = window.require('electron');

const KeyManager = ({ onKeyStatusChange }) => {
  const [keyStatus, setKeyStatus] = useState({
    checked: false,
    exists: false,
    privateKeyPath: '',
    publicKeyPath: ''
  });

  const [status, setStatus] = useState({
    message: '',
    isError: false,
    loading: false
  });

  useEffect(() => {
    checkKeys();
  }, []);

  const checkKeys = async () => {
    try {
      setStatus({ message: '正在检查SSH密钥...', isError: false, loading: true });
      const result = await ipcRenderer.invoke('check-ssh-keys');
      setKeyStatus({
        checked: true,
        exists: result.privateKeyExists && result.publicKeyExists,
        privateKeyPath: result.privateKeyPath,
        publicKeyPath: result.publicKeyPath
      });
      onKeyStatusChange(result.privateKeyExists && result.publicKeyExists);
      setStatus({ message: '', isError: false, loading: false });
    } catch (error) {
      setStatus({ message: `检查SSH密钥时出错: ${error.message}`, isError: true, loading: false });
    }
  };

  const generateKeys = async () => {
    try {
      if (keyStatus.exists) {
        const confirmed = window.confirm('检测到已存在的SSH密钥，重新生成将覆盖现有密钥。是否继续？');
        if (!confirmed) {
          return;
        }
      }
      
      setStatus({ message: '正在生成SSH密钥...', isError: false, loading: true });
      await ipcRenderer.invoke('generate-ssh-keys');
      await checkKeys();
      setStatus({ message: 'SSH密钥生成成功', isError: false, loading: false });
    } catch (error) {
      setStatus({ message: `生成SSH密钥时出错: ${error.message}`, isError: true, loading: false });
    }
  };

  const deleteKeys = async () => {
    if (!window.confirm('确定要删除当前SSH密钥吗？此操作不可恢复。')) return;
    try {
      setStatus({ message: '正在删除密钥...', isError: false, loading: true });
      const result = await ipcRenderer.invoke('delete-ssh-keys');
      if (result.success) {
        setStatus({ message: '密钥已删除', isError: false, loading: false });
        await checkKeys();
      } else {
        setStatus({ message: '删除失败: ' + result.message, isError: true, loading: false });
      }
    } catch (error) {
      setStatus({ message: `删除密钥时出错: ${error.message}`, isError: true, loading: false });
    }
  };

  const importKey = async () => {
    try {
      setStatus({ message: '正在导入密钥...', isError: false, loading: true });
      const result = await ipcRenderer.invoke('import-ssh-key');
      if (result.success) {
        setStatus({ message: '密钥导入成功', isError: false, loading: false });
        await checkKeys();
      } else {
        const isActualError = result.message !== "未选择文件";
        setStatus({ message: '导入操作: ' + result.message, isError: isActualError, loading: false });
      }
    } catch (error) {
      setStatus({ message: `导入密钥时出错: ${error.message}`, isError: true, loading: false });
    }
  };

  return (
    <div className="key-manager">
      <h2>本地SSH密钥</h2>
      <div className="key-status">
        {keyStatus.checked && (
          <div className="status-info">
            {keyStatus.exists ? (
              <>
                <p>私钥路径: {keyStatus.privateKeyPath}</p>
                <p>公钥路径: {keyStatus.publicKeyPath}</p>
                <p className="warning-text">注意：重新生成密钥将覆盖现有密钥</p>
              </>
            ) : (
              <p style={{ color: '#999' }}>未检测到密钥</p>
            )}
          </div>
        )}
      </div>
      <div className="button-group">
        <button onClick={checkKeys} disabled={status.loading} className="secondary-button">
          <span role="img" aria-label="search">🔍</span> 检查密钥
        </button>
        <button onClick={generateKeys} disabled={status.loading} className="primary-button">
          <span role="img" aria-label="key">🔑</span> {keyStatus.exists ? '重新生成密钥' : '生成密钥'}
        </button>
        <button onClick={importKey} disabled={status.loading} className="secondary-button">
          <span role="img" aria-label="import">📥</span> 导入已有密钥
        </button>
        <button onClick={deleteKeys} disabled={status.loading || !keyStatus.exists} className="secondary-button">
          <span role="img" aria-label="delete">🗑️</span> 删除密钥
        </button>
      </div>
      {status.message && (
        <div className={`status-message ${status.isError ? 'error' : ''}`}>
          {status.message}
          {status.loading && <span className="loading-spinner"></span>}
        </div>
      )}
    </div>
  );
};

export default KeyManager; 